from flask import Blueprint, render_template, request, redirect, session
from utils.db import fetch_one  # 导入数据库查询函数
import hashlib

# 蓝图对象
ac = Blueprint("account", __name__)

@ac.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html") 
        # 渲染登录页面 将Python变量注入HTML模板，自动在templates目录查找模板文件

    role = request.form.get("role")
    mobile = request.form.get("mobile")
    
    password = request.form.get("password")
    new = hashlib.md5(password.encode())
    newpwd = new.hexdigest()


    print(role, mobile, password)

    # 连接MySQL并执行SQL语句查询用户密码是否正确
    #result 默认返回元组，所以我们要想办法让它返回的是字典
    result =  fetch_one("SELECT * FROM user_info WHERE mobile=%s AND password=%s AND role=%s", (mobile, newpwd, role))

    print(result)

    if result:
        #登录成功＋跳转
        session['user_info'] = {'role': result['role'], 'real_name': result['real_name'], 'id': result['id']} #登录凭证
        return redirect('/order/list')#重定向到新URL
    
    else:
        return render_template("login.html", error = "用户名或密码错误")

    # 去数据库验证
    return "ok"


@ac.route("/users")
def users():
    return "用户列表"
